package myblog.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import myblog.dao.LogDao;
import myblog.entity.LogEntity;
import myblog.vo.LogsVo;

public class LogDaoImpl extends JdbcDaoSupport implements LogDao {

	@Override
	public List<LogEntity> list() {
		String sql = "select * from log";

		JdbcTemplate jt = getJdbcTemplate();

		List<LogEntity> logList = jt.query(sql, new LogRowMapper());

		return logList;
	}

	class LogRowMapper implements RowMapper {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

			LogEntity entity = new LogEntity();

			entity.setLogid(rs.getString("logid"));
			entity.setLogtitle(rs.getString("logtitle"));
			entity.setLogcontent(rs.getString("logcontent"));
			entity.setUsername(rs.getString("username"));
			entity.setCreatedate(rs.getString("createdate"));

			return entity;
		}
	}

	@Override
	public void addlog(LogsVo logVo) {
		JdbcTemplate jt = getJdbcTemplate();

		String sql = "insert into log(logtitle,logcontent,username) values(?,?,?)";

		// 构建参数数组
		Object[] args = { logVo.getLogtitle(), logVo.getLogcontent(),
				logVo.getUsername() };

		jt.update(sql, args);

	}

	@Override
	public void editlog(LogsVo logVo) {
		JdbcTemplate jt = getJdbcTemplate();

		String sql = "update log set logtitle= ?, logcontent = ?, username = ? where logid = ?";

		// 构建参数数组
		Object[] args = { logVo.getLogtitle(), logVo.getLogcontent(),
				logVo.getUsername(), logVo.getLogid() };

		jt.update(sql, args);

	}

	@Override
	public void dellog(String logid) {
		JdbcTemplate jt = getJdbcTemplate();

		String sql = "delete from log where logid = ?";

		// 构建参数数组
		Object[] args = { logid };

		jt.update(sql, args);

	}

	@Override
	public LogEntity getlog(String logid) {
		JdbcTemplate jt = getJdbcTemplate();

		String sql = "select * from log where logid = ?";

		// 构建参数数组
		Object[] args = { logid };

		LogEntity logEntity = (LogEntity) jt.queryForObject(sql, args,
				new LogRowMapper());

		return logEntity;
	}

}
